package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.enums.LoginTypeEnum;
import com.corpgovernment.api.organization.model.user.login.MbUserLoginVo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.organization.factory.LoginSourceServiceFactory;
import com.ctrip.corp.obt.auth.client.handler.token.JwtTokenHandler;
import com.ctrip.corp.obt.auth.core.token.OAuth2AccessToken;
import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

/**
 * @author jhxue
 * @create 2022-02-18-14:21
 */
@Service
@Slf4j
public class AuthorizationCodeLoginService extends AbstractLoginService {

	@Autowired
	private JwtTokenHandler jwtTokenHandler;
	@Autowired
	private LoginSourceServiceFactory loginSourceServiceFactory;

	@Override
	public UserLoginResponseVo login(MbUserLoginVo request) {
		String clientId = TenantContext.getClientId();
		if (clientId == null) {
			throw new CommonException(1031, "No client id was found");
		}
		String code = request.getCode();
		if (code == null) {
			throw new CommonException(1032, "No code was found");
		}
		OAuth2AccessToken oAuth2AccessToken = jwtTokenHandler.createAccessTokenInAuthCodeMode(
				clientId,
				code,
				false,
				Collections.singletonMap("source", request.getSource()));
		Map<String, Object> userInfoByAccessToken = jwtTokenHandler.getUserInfoByAccessToken(clientId, oAuth2AccessToken.getValue());
		BaseUserInfo userInfo = JsonUtils.convert(userInfoByAccessToken, BaseUserInfo.class);
		userInfo.setToken((String) userInfoByAccessToken.get("id"));
		UserLoginResponseVo response = new UserLoginResponseVo();
		response.setToken(oAuth2AccessToken.getValue())
				.setUserName(userInfo.getUserName())
				.setUid(userInfo.getUid())
				.setAccountName(userInfo.getAccountName())
				.setBgUser(userInfo.getBgUser())
				.setCid((String) userInfoByAccessToken.get("cid"))
//				.setPhoneNum(mbUserLogin.getPhoneNum())
//				.setCountryCode(mbUserLogin.getCountryCode())
				.setShowManage(false)
				.setRefreshToken(oAuth2AccessToken.getRefreshToken().getValue())
				.setExpiration(oAuth2AccessToken.getExpiration());
		return loginSourceServiceFactory.getLoginSourceService(request.getSource()).process(userInfo, response, LoginTypeEnum.AUTHORIZATION_CODE);
	}

	@Override
	public String getLoginType() {
		return LoginTypeEnum.AUTHORIZATION_CODE.toString();
	}

}
